<?php

namespace app\models;

use app\models\user\User;
use Yii;

/**
 * This is the model class for table "award_result".
 *
 * @property int $id
 * @property string $name 标题
 * @property string|null $desc 说明
 * @property string $create_time
 * @property string $update_time
 * @property int $user_id
 * @property float $balance
 * @property float $score
 * @property int $award_id
 * @property resource|null $log
 * @property int $status 0 待发放, 1 已发放
 */
class AwardResult extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'award_result';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['desc', 'log'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['user_id', 'award_id', 'status'], 'integer'],
            [['balance', 'score'], 'number'],
            [['name'], 'string', 'max' => 255],

            [['award_sn'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'desc' => 'Desc',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'user_id' => 'User ID',
            'balance' => 'Balance',
            'score' => 'Score',
            'award_id' => 'Award ID',
            'log' => 'Log',
            'status' => 'Status',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    // 奖项
    public function getAward()
    {
        return $this->hasOne(AwardList::class, ['id' => 'award_id']);
    }

    // 中奖会员
    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id'])
            ->select(['id', 'mobile', 'avatar', 'nickname', 'base64Image']);
    }
}
